package com.zq.learn.springbatch.combination;

import com.zq.learn.springbatch.combination.quartz.TestTask;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static org.quartz.CronScheduleBuilder.cronSchedule;

/**
 * OrderService
 *
 * @author ZhangQi
 * @date 2020/2/19
 */
@Service
public class OrderService {
  Logger logger= LoggerFactory.getLogger(OrderService.class);
  @Autowired
  private Scheduler scheduler;

  /**
   * 动态操作任务测试
   * @param status 操作：0-创建任务；1-暂停任务；2-恢复任务；3-删除任务；
   * @throws SchedulerException
   */
  public void orderTest(Integer status) throws SchedulerException {
    logger.info("操作：==============》status="+status);
    if(status==0){
      JobDetail task2 =
        JobBuilder.newJob(TestTask.class).withIdentity("OrderTask").build();
      CronTrigger trigger2 =
        TriggerBuilder.newTrigger().forJob(task2).withIdentity("OrderTrigger")
          .withSchedule(cronSchedule("*/4 * * * * ?")).build();
      scheduler.scheduleJob(task2,trigger2);
    }else {
      JobKey jobKey = JobKey.jobKey("OrderTask");
      if(status==1) {
        //暂停
        scheduler.pauseJob(jobKey);
      }else if(status==2){
        //恢复
        scheduler.resumeJob(jobKey);
      }else if(status==3){
        TriggerKey triggerKey = TriggerKey.triggerKey("OrderTrigger");
        scheduler.unscheduleJob(triggerKey);
        scheduler.deleteJob(jobKey);
      }
    }
  }
}
